package com.common.util;

import com.li.model.TableCol;
import com.li.model.TableData;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MyFileUtil {
    public static boolean fileUpload(CommonsMultipartFile file, HttpServletRequest request,String savePath){

        String path = request.getServletContext().getRealPath(savePath);
        //如果路径不存在则创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件的保存地址为:"+realPath);
        //通过CommonsMultipartFile对象直接写文件
        try {
            file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static boolean fileDownload( HttpServletResponse response,String fileName,String savePath){



        //1.设置response响应头
        response.reset();//设置页面不要缓存，清空buffer
        response.setCharacterEncoding("UTF-8");//设置字符编码
        response.setContentType("multipart/form-data");
        //设置响应头
        try {
            response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
        File file = new File(savePath,fileName);
        //2.读取文件，文件输入流
        InputStream in = null;
        OutputStream out =null;
        try {
            in = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] buffer = new byte[1024*4];
            int len = 0;
            while ((len=in.read(buffer))!=-1){
                out.write(buffer,0,len);
                out.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(savePath+file+"未找到");
            return false;
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    public static TableData getFileContent(String fileRealPath) throws IOException {
//        ArrayList<List> table = new ArrayList<>(100);
//        ArrayList<String> rowData ;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        int i=0;
        int j=0;
        //1.获取文件输入流
        TableData tableData = new TableData();
        FileInputStream in = new FileInputStream(fileRealPath);
        //2.得到对应的工作簿
        Workbook workbook ;
        //版本判断
        String suffix = fileRealPath.substring(fileRealPath.lastIndexOf(".")+1);
        if ("xls".equals(suffix)){
            //03版本
            System.out.println("03版本："+suffix);
            workbook = new HSSFWorkbook(in);
        }else{
            //07版本
            System.out.println("07版本："+suffix);
            workbook = new XSSFWorkbook(in);
        }
        //3.得到对应的表
        Sheet sheet = workbook.getSheetAt(0);



        //4.遍历所有的行数量
        //通过getPhysicalNumberOfRows()方法得到该文件中行的数量
        int rowCount = sheet.getPhysicalNumberOfRows();

        //获取标题列
        Row title = sheet.getRow(0);
        Row firstDataRow = sheet.getRow(1);
        //获取列数量
        int columnCount = title.getPhysicalNumberOfCells();
        //创建列对象
        Object[] tableColList = new Object[columnCount];
        Cell cell = null;
        Row row = null;
        //初始化列对象
        for (int k = 0; k <columnCount; k++) {
            cell = firstDataRow.getCell(k);
            //数据类型判断
            if (cell != null) {
                //得到单元格的数据类型
                CellType cellType = cell.getCellType();
                //匹配单元格的数据类型
                switch (cellType) {
                    case STRING://字符串
                        TableCol<String> tableCol = new TableCol<>();
                        tableCol.setDataType("String");
                        tableCol.setTitle(title.getCell(k).getStringCellValue());
                        tableCol.setIndex(k);
                        String[] data = new String[rowCount];
                        for (int l = 1; l < rowCount; l++) {
                            data[l] = sheet.getRow(l).getCell(k).getStringCellValue();
                        }
                        tableCol.setData(data);
                        tableColList[k] = tableCol;
                        break;
                    case BOOLEAN://布尔值
                        TableCol<Boolean> tableCol1 = new TableCol<>();
                        tableCol1.setDataType("boolean");
                        tableCol1.setTitle(title.getCell(k).getStringCellValue());
                        tableCol1.setIndex(k);
                        Boolean[] data1 = new Boolean[rowCount];
                        for (int l = 1; l < rowCount; l++) {
                            data1[l] = sheet.getRow(l).getCell(k).getBooleanCellValue();
                        }
                        tableCol1.setData(data1);
                        tableColList[k] = tableCol1;
                        break;
                    case BLANK://空的
                        TableCol<Object> tableCol2 = new TableCol<>();
                        tableCol2.setDataType("blank");
                        tableCol2.setTitle(title.getCell(k).getStringCellValue());
                        tableCol2.setIndex(k);
                        Object[] data2 = new Object[rowCount];
                        for (int l = 1; l < rowCount; l++) {
                            data2[l] = sheet.getRow(l).getCell(k).getStringCellValue();
                        }
                        tableCol2.setData(data2);
                        tableColList[k] = tableCol2;
                        break;
                    case NUMERIC://数字
                        //如果是日期类型，则将其格式化为字符串类型
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            TableCol<Date> tableCol3 = new TableCol<>();
                            tableCol3.setDataType("date");
                            tableCol3.setTitle(title.getCell(k).getStringCellValue());
                            tableCol3.setIndex(k);
                            Date[] data3 = new Date[rowCount];
                            for (int l = 1; l < rowCount; l++) {
                                data3[l] = sheet.getRow(l).getCell(k).getDateCellValue();
                            }
                            tableCol3.setData(data3);
                            tableColList[k] = tableCol3;
                        } else {
                            TableCol<Double> tableCol4 = new TableCol<>();
                            tableCol4.setDataType("double");
                            tableCol4.setTitle(title.getCell(k).getStringCellValue());
                            tableCol4.setIndex(k);
                            Double[] data4 = new Double[rowCount];
                            for (int l = 1; l < rowCount; l++) {
                                data4[l] = sheet.getRow(l).getCell(k).getNumericCellValue();
                            }
                            tableCol4.setData(data4);
                            tableColList[k] = tableCol4;
                        }
                        break;
                    case ERROR:
                        TableCol<Object> tableCol5 = new TableCol<>();
                        tableCol5.setDataType("error");
                        tableCol5.setTitle(title.getCell(k).getStringCellValue());
                        tableCol5.setIndex(k);
                        Object[] data5 = new Object[rowCount];
                        for (int l = 1; l < rowCount; l++) {
                            data5[l] = sheet.getRow(l).getCell(k).getErrorCellValue();
                        }
                        tableCol5.setData(data5);
                        tableColList[k] = tableCol5;
                        break;
                }
            }
        }


        //取出数据
        //遍历所有行 第0行为标题
        tableData.setColList(tableColList);
        return tableData;
    }
}
